import 'package:flutter/material.dart';
import 'debug_tool.dart';
import 'photo_texture_controller.dart';

/// 使用外接纹理方式展示图库图片
/// 注意：
/// - 该 widget 仅作被动地展示；
/// - controller 的生命周期需要由外部管理；
class PhotoTextureWidget extends StatefulWidget {
  final PhotoTextureController controller;
  final Function debugLabel;
  PhotoTextureWidget(this.controller, {this.debugLabel});

  @override
  _PhotoTextureWidgetState createState() => _PhotoTextureWidgetState();
}

class _PhotoTextureWidgetState extends State<PhotoTextureWidget> {
  VoidCallback _listener;
  int _textureId;

  Function debugBase;

  @override
  void initState() {
    super.initState();

    debugBase = () => 'PhotoTextureWidget(${this.widget.debugLabel()})';

    _listener = () {
      final int newTextureId = widget.controller.textureId;
      if (newTextureId != _textureId) {
        setState(() {
          _textureId = newTextureId;
        });
      }
    };

    _textureId = widget.controller.textureId;
    // Need to listen for initialization events since the actual texture ID
    // becomes available after asynchronous initialization finishes.
    widget.controller.addListener(_listener);

    dprint('${debugBase()} - initState');
  }

  @override
  void dispose() {
    dprint('${debugBase()} - dispose');
    // dprint('hasListener: ${widget.controller.hasListeners}');
    widget.controller.disposeTexture();
    super.dispose();
  }

  @override
  void didUpdateWidget(PhotoTextureWidget oldWidget) {
    super.didUpdateWidget(oldWidget);
    oldWidget.controller.removeListener(_listener);
    _textureId = widget.controller.textureId;
    widget.controller.addListener(_listener);

    dprint('${debugBase()} - didUpdateWidget');
  }

  @override
  void deactivate() {
    super.deactivate();
    widget.controller.removeListener(_listener);

    // dprint('${debugBase()} - deactivate');
  }

  Widget _buildAspectTexture() {
    Widget widget = Texture(textureId: _textureId);

    final asset = this.widget.controller.asset;
    widget = AspectRatio(
      aspectRatio: asset.width / asset.height,
      child: widget,
    );

    widget = Align(
      alignment: Alignment.center,
      child: widget,
    );

    return widget;
  }

  @override
  Widget build(BuildContext context) {
    dprint('${debugBase()} - build');

    widget.controller.initialize().then((_) {
      widget.controller.update(width: 200);
    });
    _textureId = widget.controller.textureId;
    return _textureId == null ? Container() : _buildAspectTexture();
  }
}
